<template>
    <div class="">
        <el-dialog  :title="addForm.id>0 ? '修改居民':'添加居民'" :close-on-click-modal="false" style="width: 650px;" v-model="dialogVisible" :before-close="handleClose">
            <el-form :rules="rules" ref="ruleFormRef" :model="addForm" class="elform" label-width="auto">
                <el-form-item label="图片" class="photo">
                    <el-upload class="avatar-uploader" :headers="headers" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.photo" :src="baseUrl + addForm.photo" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="楼栋">
                    <BuildSelect :checkStrictly="false" @update="cascaderChange" :defaultValue="buildid"></BuildSelect>
                </el-form-item>
                <el-form-item label="房间">
                    <el-select clearable v-model="addForm.houseid" style="width:120px" placeholder="请选择状态">
                        <el-option v-for="item in houseList" :label="item.houseno" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name" />
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="addForm.sex">
                        <el-radio value="1" size="large">男</el-radio>
                        <el-radio value="2" size="large">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="民族">
                    <el-input v-model="addForm.nation" />
                </el-form-item>
                <el-form-item label="籍贯">
                    <el-input v-model="addForm.usernative" />
                </el-form-item>
                <el-form-item label="证件">
                    <el-input v-model="addForm.cardid" />
                </el-form-item>
                <el-form-item label="电话">
                    <el-input v-model="addForm.mobile" />
                </el-form-item>
                <el-form-item label="类型">
                    <el-select clearable v-model="addForm.usertype" style="width:120px" placeholder="请选择状态">
                        <el-option label="业主" value="1" />
                        <el-option label="租户" value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserInfo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import BuildSelect from "./BuildSelect.vue"
import {adduserinfo} from '../service/userinfo/userinfolist'
import { gethouse } from "../service/house/house";
import {addFromType} from '../views/userinfo/userinfo.vue'
import type { FormInstance, FormRules } from 'element-plus'

const headers = {
    Authorization: sessionStorage.getItem("token")
}
const uploadUrl = import.meta.env.VITE_BASE_URL + "upload/add";
const baseUrl = import.meta.env.VITE_IMG_URL
const buildid = ref(0)
type  houseType={
    houseno: string,
    id:number
}

const porps =  defineProps(["addForm"])
const houseList = ref<houseType[]>([])
//获取房屋列表
const getHouseList = async () => {
    const res = await gethouse({houseid:buildid})
    console.log(res);   
    
    houseList.value= res.data.list
}
//提交
const addUserInfo =async () => {
    let res:any =await adduserinfo(addForm).catch(()=>{})
    console.log(res);
    if (res.errCode == 10000) {
        ElMessage.success(res.errMsg)
        emit('update',true)
        dialogVisible.value = false
    } else {
        ElMessage.error(res.errMsg)
    }
    
}
//楼栋信息
const cascaderChange = (e: any) => {
    if (!e) {
        return buildid.value = 0
    } 
    buildid.value= e[0]
    getHouseList()
}
//图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    console.log(response);
    if (response.errCode === 10000) {
        addForm.photo = response.data;
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片需要是jpg或png格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能超过2MB!')
        return false
    }
    return true
}

const emit = defineEmits(['close','update'])
const dialogVisible = ref(true)

let addForm = reactive<addFromType>({
    id: 0,
    photo: "",
    name: "",
    houseid: null,
    usertype: null,
    sex: 0,
    mobile: "",
    usernative: "",
    cardid: "",
    nation: "",
})
const handleClose = () => {
    dialogVisible.value = false
    emit('close', [])
}



const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入姓名'))
  }  else {
    callback()
  }
}

const ruleForm = reactive({
  name: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ validator: validatePass2, trigger: 'blur' }],
})



onMounted(()=>{
    Object.assign(addForm,porps.addForm)
    if (porps.addForm.buildingid) {
        buildid.value = porps.addForm.buildingid
        getHouseList()
    }
})
</script>

<style lang="less" scoped>
@import url(../assets/userinfo/userinfoadd.less);
</style>
